<?php

class ProductService
{

    private $searchService;
    private $prodcutSearchResult;
    // private $productCacheDao; //修改记录 2011.3.27
    private $userId;
    private $useCache;

    public function __construct()
    {
        $this->searchService = C('SearchService');
        //$this->productCacheDao = new ProductCacheDao();//修改记录 2011.3.27
        $this->useCache = true;
        $this->userId = 0;
    }

    public function getProductById($id, $detail=false)
    {
        $product = $this->getTaoKeProductByNumId($id);
        if (!$product && $detail)
        {
            $product = $this->getTaobaoItem($id);
        }
        return $product;
    }

    public function getTaoKeProductByNumId($id, $fields=array())
    {
        //从cache中取数据
        $product = $this->getDataFromCache($id, 'detail');
        if ($product)
        {
            if(!empty($product['click_url']))
            {
                return $product;
            }            
        }
        //初始化查询的字段
        $cols = split(',', 'iid,click_url,shop_click_url,seller_credit_score,detail_url,num_iid,title,nick,type,cid,seller_cids,input_pids,input_str,pic_url,num,valid_thru,list_time,delist_time,stuff_status,location,price,post_fee,express_fee,ems_fee,has_discount,freight_payer,has_invoice,has_warranty,has_showcase,modified,increment,auto_repost,approve_status,postage_id,product_id,auction_point,property_alias,outer_id,is_virtural,is_taobao,is_ex,video,is_3D,one_station,desc');
        $fields = $this->checkFields($cols, $fields);

        $apiSetting = C('SettingService')->get('api_setting', true);
        //参数
        $params = array(
            'method' => 'taobao.taobaoke.items.detail.get',
            'fields' => $fields,
            'nick' => $apiSetting['taobao_api_nick'],
            'num_iids' => $id,
            'outer_code' => $this->userId,
        );

        $num = $apiSetting['taobao_api_num'];
        if ($num <= 0)
        {
            $num = 1;
        }
        else if ($num > 3)
        {
            $num = 3;
        }
        for ($i = 0; $i < $num; $i++)
        {
            $tmp = $this->searchService->getResult($params);
            if ($tmp && !array_key_exists('error_response', $tmp))
            {
                break;
            }
        }
        if (!$tmp || !array_key_exists('taobaoke_items_detail_get_response', $tmp))
        {
            return false;
        }

        $product = array_key_exists('taobaoke_item_details', $tmp['taobaoke_items_detail_get_response']) ? $tmp['taobaoke_items_detail_get_response']['taobaoke_item_details']['taobaoke_item_detail'][0] : false;

        if (empty($product['click_url']) or empty($product['shop_click_url'])) //判断是否取到链接 
        {
            $params1 = array(
                'method' => 'taobao.taobaoke.items.convert',
                'fields' => 'click_url,shop_click_url',
                'nick' => $apiSetting['taobao_api_nick'],
                'num_iids' => $id,
                'outer_code' => $this->userId,
            );

            for ($i = 0; $i < $num; $i++)
            {
                $tmp1 = $this->searchService->getResult($params1);
                if ($tmp1 && !array_key_exists('error_response', $tmp1))
                {
                    break;
                }
            }
            if (array_key_exists('taobaoke_items_convert_response', $tmp1))
            {
                $product['click_url']=$tmp1['taobaoke_items_convert_response']['taobaoke_items']['taobaoke_item'][0]['click_url'];
                $product['shop_click_url']=$tmp1['taobaoke_items_convert_response']['taobaoke_items']['taobaoke_item'][0]['shop_click_url'];                
            }
        }

        //保存到cache中
        $this->saveDataToCache($id, 'detail', $product);
        return $product;
    }

    public function getList($con, $fields=array(), $cache=0, $position='')
    {
        //从缓存中获取
        $cacheId = md5(serialize($con) . serialize($fields) . $cache . $position);
        if ($cache > 0)
        {
            $result = $this->getListFromCache($cacheId);
            if ($result)
            {
                return $result;
            }
        }

        $this->searchTaoKeProducts($con, $fields, false);
        $result = $this->getProductList();
        //更新cache
        if ($cache > 0 && $result)
        {
            $this->saveListToCache($cacheId, $result, $cache);
        }
        return $result;
    }

    public function searchTaoKeProducts($con, $fields=array(), $cache=true)
    {
        //初始化查询的字段
        $cols = split(',', 'iid,num_iid,title,nick,pic_url,price,click_url,commission,commission_rate,commission_num,commission_volume,shop_click_url,seller_credit_score,item_location');
        $fields = $this->checkFields($cols, $fields);

        if (array_key_exists('ids', $con))
        {
            //有num_iid
            if ($con['ids'] != '')
            {
                return $this->getProductListByIds($con['ids'], explode(',', $fields), $cache);
            }
            else
            {
                unset($con['ids']);
            }
        }

        if (!$con['cid'])
        {
            unset($con['cid']);
        }

        $apiSetting = C('SettingService')->get('api_setting', true);

        //参数
        $params = array(
            'method' => 'taobao.taobaoke.items.get',
            'fields' => $fields,
            'nick' => $apiSetting['taobao_api_nick'],
        );
        $params = array_merge($params, $con);

        $products = false;

        //       if ($params['sort'] == "delistTime_desc" && $params['page_no'] < 4)
        //      {
        //          $products = false;
        //      }
        //      else
        //      {
        //          $cacheId = md5(serialize($params));
        //         $products = $this->getDataFromCache($cacheId, 'list');
        //     }

        if ($cache)
        {
            $cacheId = md5(serialize($params));
            $products = $this->getDataFromCache($cacheId, 'list');
        }
        if (!$products)
        {
            $num = $apiSetting['taobao_api_num'];
            if ($num <= 0)
            {
                $num = 1;
            }
            else if ($num > 3)
            {
                $num = 3;
            }
            for ($i = 0; $i < $num; $i++)
            {
                $tmp = $this->searchService->getResult($params);
                if ($tmp && !array_key_exists('error_response', $tmp))
                {
                    break;
                }
            }

            if (!$tmp || !array_key_exists('taobaoke_items_get_response', $tmp))
            {
                $this->prodcutSearchResult = false;
                return false;
            }

            $products = $tmp['taobaoke_items_get_response'];
            if ($cache)
            {
                $this->saveDataToCache($cacheId, 'list', $products);
            }
        }

        $this->prodcutSearchResult = $products;
        return $products;
    }

    private function getProductListByIds($ids, $fields=array(), $cache=true)
    {
        $colsMap = array('iid' => 'iid', 'num_iid' => 'num_iid', 'title' => 'title', 'nick' => 'nick', 'pic_url' => 'pic_url', 'price' => 'price', 'click_url' => 'click_url', 'shop_click_url' => 'shop_click_url', 'seller_credit_score' => 'seller_credit_score', 'item_location' => 'location');
        $colsMap2 = array();
        foreach ($colsMap as $k => $v)
        {
            $colsMap2[$v] = $k;
        }
        $tmp = array();
        foreach ($fields as $f)
        {
            if (array_key_exists($f, $colsMap))
            {
                $tmp[] = $colsMap[$f];
            }
        }
        $fields = implode(',', $tmp);
        $ids = str_replace('，', ',', $ids);

        $result = false;
        if ($cache)
        {
            $cacheId = md5($ids . $fields);
            $result = $this->getDataFromCache($cacheId, 'idlist');
        }

        if (!$result)
        {
            $apiSetting = C('SettingService')->get('api_setting', true);

            $products = array();
            $idList = explode(',', $ids);
            for ($ii = 0; $ii < count($idList); $ii+=10)
            {
                $maxLen = count($idList) - $ii >= 10 ? 10 : count($idList) - $ii;
                //参数
                $params = array(
                    'method' => 'taobao.taobaoke.items.detail.get',
                    'fields' => $fields,
                    'nick' => $apiSetting['taobao_api_nick'],
                    'num_iids' => implode(',', array_slice($idList, $ii, $maxLen))
                );

                $num = $apiSetting['taobao_api_num'];
                if ($num <= 0)
                {
                    $num = 1;
                }
                else if ($num > 3)
                {
                    $num = 3;
                }
                for ($i = 0; $i < $num; $i++)
                {
                    $tmp = $this->searchService->getResult($params);
                    if ($tmp && !array_key_exists('error_response', $tmp))
                    {
                        break;
                    }
                }
                if (!$tmp || !array_key_exists('taobaoke_items_detail_get_response', $tmp))
                {
                    $this->prodcutSearchResult = false;
                    return false;
                }

                foreach ($tmp['taobaoke_items_detail_get_response']['taobaoke_item_details']['taobaoke_item_detail'] as $v)
                {
                    $tmp = array();
                    foreach ($v as $k => $vv)
                    {
                        if ($k != 'item')
                        {
                            $tmp[$colsMap2[$k]] = $vv;
                        }
                        else
                        {
                            foreach ($vv as $vvk => $vvv)
                            {
                                $tmp[$colsMap2[$vvk]] = $vvv;
                            }
                        }
                    }

                    $products[] = $tmp;
                }
            }

            $result['taobaoke_items']['taobaoke_item'] = $products;
            $result['total_results'] = count($products);

            if ($cache)
            {
                $this->saveDataToCache($cacheId, 'idlist', $result);
            }
        }

        $this->prodcutSearchResult = $result;
        return $result;
    }

    private function getDataFromCache($id, $type)
    {
        if (!$this->useCache)
        {
            return false;
        }
        $cacheCfg = C('LtConfig')->get('cache.product');

        if ($type == 'list')
        {
            $enable = $cacheCfg['listcacheenable'];
            $period = $cacheCfg['listcacheperiod'];
            $cacheDir = $cacheCfg['listdir'];
            $newperiod = 35;
        }
        else
        {
            $enable = $cacheCfg['detailcacheenable'];
            $period = $cacheCfg['detailcacheperiod'];
            $cacheDir = $cacheCfg['detaildir'];
            $newperiod = 45;
        }

        if (!$enable)
        {
            return false;
        }

        $ccs = C('CompressCacheService');
        $d = $ccs->getCacheDirById($id);
        if ($d === false)
        {
            return false;
        }
        $result = $ccs->getCacheData($cacheDir, $d, $id);
        //检查过期时间
        if ($result)
        {
            $du = C('DateUtil');
            //没有缓存时间或者缓存时间距离当前时间已经超过设定的cache时间
            /*
              $time=time();
              if ($du->dateAdd('d', $newperiod, $result['cache_time']) < $time)
              {
              if (time() % 80 == 0)
              {
              $num=rand();
              if($num%20==0)
              {
              $result = false;
              }
              }
              }
             */
            if (!array_key_exists('cache_time', $result) || $du->dateAdd('d', $period, $result['cache_time']) < time())
            {
                if (time() % 5 == 0)
                {
                    $num = rand();
                    if ($num % 3 == 0)
                    {
                        $result = false;
                    }
                }
            }
        }

        //  if ($result)
        //  {
        //      $this->updateProductCache($id, $type);
        //  }
        return $result;
    }

    private function saveDataToCache($id, $type, $data)
    {
        if (!$data || !$this->useCache)
        {
            return false;
        }

        $cacheCfg = C('LtConfig')->get('cache.product');
        if ($type == 'list')
        {
            $enable = $cacheCfg['listcacheenable'];
            $period = $cacheCfg['listcacheperiod'];
            $cacheDir = $cacheCfg['listdir'];
        }
        else
        {
            $enable = $cacheCfg['detailcacheenable'];
            $period = $cacheCfg['detailcacheperiod'];
            $cacheDir = $cacheCfg['detaildir'];
        }

        if (!$enable)
        {
            return false;
        }

        $ccs = C('CompressCacheService');
        $d = $ccs->getCacheDirById($id);
        if ($d === false)
        {
            return false;
        }
        $data['cache_time'] = date('Y-m-d H:i:s');
        $ccs->setCacheData($cacheDir, $d, $id, $data);

        //$this->updateProductCache($id, $type);
        return true;
    }

    private function updateProductCache($id, $type)
    {
        //修改记录 2011.3.27
        return;

        //##########################
        if ($type == 'list')
        {
            $prefix = 'l_';
            $type = 0;
        }
        else
        {
            $prefix = 'd_';
            $type = 1;
        }
        $id = $prefix . $id;
        $tmp = $this->productCacheDao->get($id);

        if ($tmp)
        {
            $this->productCacheDao->update($id, array('updated' => date('Y-m-d'), 'visit_num' => $tmp['visit_num'] + 1));
        }
        else
        {
            $this->productCacheDao->add(array('id' => $id, 'updated' => date('Y-m-d'), 'type' => $type, 'visit_num' => 1));
        }
    }

    public function delCacheData($id, $type)
    {
        $cacheCfg = C('LtConfig')->get('cache.product');
        if ($type == 'list')
        {
            $cacheDir = $cacheCfg['listdir'];
        }
        else
        {
            $cacheDir = $cacheCfg['detaildir'];
        }

        $ccs = C('CompressCacheService');
        $d = $ccs->getCacheDirById($id);
        if ($d === false)
        {
            return false;
        }

        $result = $ccs->delCacheData($cacheDir, $d, $id);
        return $result;
    }

    public function getTotalProcuct()
    {
        if (is_array($this->prodcutSearchResult) && array_key_exists('total_results', $this->prodcutSearchResult))
        {
            return $this->prodcutSearchResult['total_results'];
        }
        return 0;
    }

    public function getProductList()
    {
        if (is_array($this->prodcutSearchResult) && array_key_exists('taobaoke_items', $this->prodcutSearchResult))
        {
            return $this->prodcutSearchResult['taobaoke_items']['taobaoke_item'];
        }
        return false;
    }

    public function getListUrl($keyword)
    {
        $apiSetting = C('SettingService')->get('api_setting', true);

        $params = array(
            'method' => 'taobao.taobaoke.listurl.get',
            'nick' => $apiSetting['taobao_api_nick'],
            'q' => $keyword,
        );
        $tmp = $this->searchService->getResult($params);
        if (!$tmp || !array_key_exists('taobaoke_listurl_get_response', $tmp))
        {
            return false;
        }

        $url = $tmp['taobaoke_listurl_get_response']['taobaoke_item']['keyword_click_url'];
        //$url = str_replace('mm_17538449_0_0', 'mm_28478470_0_0', $url);
        return $url;
    }

    public function setUserId($id)
    {
        $this->userId = $id;
        $this->useCache = $id > 0 ? false : true;
    }

    private function getTaobaoItem($id)
    {
        return false;
    }

    private function checkFields($allow, $fields)
    {
        if (!empty($fields))
        {
            $tmp = array();
            foreach ($fields as $f)
            {
                if (in_array($f, $allow))
                {
                    $tmp[] = $f;
                }
            }
            $fields = $tmp;
        }
        if (empty($fields))
        {
            $fields = $allow;
        }
        $fields = implode(',', $fields);
        return $fields;
    }

    private function getListFromCache($id)
    {
        $cache = new LtCache();
        $cache->init();
        $ch = $cache->getTDG(C('LtConfig')->get('db.table.prefix') . "product" . $id);

        $result = $ch->get('list');
        return $result;
    }

    private function saveListToCache($id, $data, $ttl)
    {
        $cache = new LtCache();
        $cache->init();
        $ch = $cache->getTDG(C('LtConfig')->get('db.table.prefix') . "product" . $id);

        $tmp = $ch->get('list');
        if ($tmp !== false)
        {
            $ch->update('list', $data, $ttl);
        }
        else
        {
            $ch->add('list', $data, $ttl);
        }
    }

}

?>